<template>
  <div class="task-feedback-dialog flex-y">
    <div class="base-modal-header">
      <h3>
        {{$t('task.auditSettle')}}
      </h3>
    </div>
    <div class="base-modal-content">
      <div class="form-view-row">
        <label>{{$t('task.detail.components.serviceDegree')}}</label>
        <div class="form-view-row-content">
          <label class="degree-item"
                 v-for="item in degreeOption"
                 :key="item.value">
            <input type="radio"
                   class="hidden"
                   name="degree"
                   :value="item.value"
                   v-model="form.degree"
                   :disabled="!allowModify" />
            <span :class="['evaluate-degree-img', getDegreeImg(item.value, form.degree == item.value)]"></span>
            <span class="degree-text">{{ item.label }}</span>
          </label>
        </div>
      </div>
      <div class="form-view-row"
           v-if="evaluateConfig.useStarEvaluate && starEvaluates.length">
        <label>{{$t('task.detail.components.serviceEvaluate')}}</label>
        <div class="star-evaluate-row-content">
          <div class="star-evaluate-row"
               v-for="(name, index) in starEvaluates"
               :key="index">
            <div class="star-title">{{ name }}</div>
            <base-service-star :value="starValue[starFeilds[index]]"
                               @input="marks(starFeilds[index], $event)"
                               :handle="allowModify"></base-service-star>
          </div>
        </div>
      </div>
      <div class="form-view-row"
           v-if="evaluateConfig.useTagEvaluate && tagEvaluates.length">
        <label>{{$t('task.detail.components.serviceTag')}}</label>
        <div class="form-view-row-content evaluate-tag">
          <label class="tag-item"
                 v-for="name in tagEvaluates"
                 :key="name">
            <input type="checkbox"
                   class="hidden"
                   :value="name"
                   v-model="tagValue"
                   :disabled="!allowModify">
            <span class="evaliate-tag-item">{{ name }}</span>
          </label>
        </div>
      </div>
      <div class="form-view-row"
           v-if="evaluateContent">
        <label>{{$t('task.customerEvaluation')}}</label>
        <div class="form-view-row-content">{{ evaluateContent }}</div>
      </div>
      <div class="form-view-row">
        <label>{{$t('task.detail.components.evaluateSuggestion')}}</label>
        <div class="form-view-row-content">
          <textarea v-model="form.suggestion"
                    placeholder="请填写回访备注[最多500字]"
                    rows="3"
                    maxlength="500" />
        </div>
      </div>
    </div>
    <div slot="footer"
         class="dialog-footer flex-x jus-end">
      <el-button class="close-task-btn"
                 @click="justGuide('menu',0)"
      >{{$t('task.detail.components.reviewAndCloseTask')}}</el-button>
    </div>
  </div>
</template>

<script>
/* api */
import * as TaskApi from '@src/api/TaskApi.ts';

/* util */
import _ from 'lodash';
import i18n from '@src/locales'

export default {
  name: 'task-feedback-dialog',
  props: {
    task: {
      type: Object,
      default: () => ({})
    },
    evaluateConfig: {
      type: Object,
      default: () => ({})
    },
    justGuide: {
      type: Function
    }
  },
  data () {
    return {
      visible: false,
      pending: false,
      // TODO 国际化待办 value参数为中文
      degreeOption: [{
        value: '满意',
        label: i18n.t('task.detail.components.satisfied'),
      }, {
        value: '一般',
        label: i18n.t('task.detail.components.commonly'),
      }, {
        value: '不满意',
        label: i18n.t('task.detail.components.dissatisfied'),
      }],
      allowModify: true, // 是否可以修改客户评价
      hasFeedback: false, // 是否回访过
      evaluateContent: '', // 客户评价(自动回访)
      starValue: {}, // 选择的服务评价
      tagValue: [], // 选择的服务标签
      form: this.buildForm()
    }
  },
  computed: {
    starEvaluates () {
      return this.evaluateConfig.starEvaluates || [];
    },
    starFeilds () {
      return this.evaluateConfig.starEvaluateFeilds || [];
    },
    tagEvaluates () {
      return this.evaluateConfig.tagEvaluates || [];
    }
  },
  methods: {
    getDegreeImg (type, selected) {
      if (type === this.degreeOption[0].value) {
        return selected ? 'review-degree-satisfy-active' : 'review-degree-satisfy';
      }

      if (type === this.degreeOption[1].value) {
        return selected ? 'review-degree-commonly-active' : 'review-degree-commonly';
      }

      if (type === this.degreeOption[2].value) {
        return selected ? 'review-degree-unsatisfy-active' : 'review-degree-unsatisfy';
      }
    },
    marks (feild, value) {
      this.$set(this.starValue, feild, value);
    },
    buildForm () {
      return {
        taskId: this.task.id,
        degree: '满意',
        suggestion: '',
        evaluate: {
          tagEvaluates: this.tagValue,
          ...this.starValue
        }
      }
    },
    openDialog () {
      // 初始化数据
      this.starValue = {};
      this.tagValue = [];
      this.form = this.buildForm();

      // 判断是否回访过
      if (this.task.degree) {
        this.hasFeedback = true;
        this.form.degree = this.task.degree;
        this.form.suggestion = this.task.suggestion || '';
        this.evaluateContent = this.task.evaluateContent || '';
        this.form.evaluate = this.task.evaluateObj || {};

        // 服务标签
        if (this.evaluateConfig.useTagEvaluate && this.form.evaluate.tagEvaluates) {
          this.form.tagValue = this.tagEvaluates.filter(tags => {
            return this.form.evaluate.tagEvaluates.some(tag => tags == tag);
          })
        }

        // 服务评价
        if (this.evaluateConfig.useStarEvaluate && this.starEvaluates.length) {
          this.starEvaluates.forEach((item, i) => {
            let value = this.form.evaluate[this.starFeilds[i]];
            this.$set(this.starValue, this.starFeilds[i], value || 0);
          })
        }
      }

      // 若已回访过并且满意度设置禁用评价内容可修改时，不可修改
      this.allowModify = !(this.hasFeedback && !this.evaluateConfig.modifyEvaluate);

      this.visible = true;
    },
    async submit (autoClosed) {
      let { useStarEvaluate, starEvaluateNotNull } = this.evaluateConfig;

      // 服务评星必填校验
      if (useStarEvaluate && starEvaluateNotNull) {
        let message = [];
        for (let i = 0; i < this.starEvaluates.length; i++) {
          let name = this.starEvaluates[i];
          if (!this.starValue[this.starFeilds[i]]) {
            message.push(this.$t('task.tip.feedbackTip2', {name}));
          }
        }

        // 允许修改客户评价时
        if (message.length > 0 && this.allowModify) return this.$platform.alert(message.join('\n'));
      }

      this.pending = true;

      const checkParams = {
        id: this.task.id,
        degree: this.form.degree,
        suggestion: this.form.suggestion,
        evaluateObj: this.form.evaluate
      }

      _.assign(checkParams.evaluateObj, this.starValue);
      checkParams.evaluateObj.tagEvaluates = this.tagValue;

      // 先判断是否需要高级审批
      let approveParams = {
        taskId: this.task.id,
        action: 'review'
      }

      const approveResult = await TaskApi.checkNeedVipApprove(approveParams);
      if (approveResult.success && approveResult.result.needVipApprove) {
        this.visible = false;
        this.pending = false;

        this.$emit('proposeApprove', approveResult.result);
        return;
      }

      // 回访是否需要审批
      const result = await this.$http.post(`/task/approve/degreeForView?autoClosed=${autoClosed}`, checkParams);
      // TODO 需要审批判断改成errorCode
      if (!result.succ && Number(result.errorCode) == 10003) {
        this.visible = false;
        this.pending = false;

        this.$emit('proposeApprove', result.data);
        return;
      }

      if (!await this.$platform.confirm(this.$t('task.tip.feedbackTip3'))) return this.pending = false;

      const params = _.cloneDeep(this.form);
      params.autoClosed = autoClosed;

      TaskApi.reviewTask(params).then((res) => {
        if (res.success) {
          this.$platform.notification({
            type: 'success',
            title: this.$t('task.tip.feedbackTip4')
          })

          window.location.reload();
        } else {
          this.$platform.alert(res.message);
          this.pending = false;
        }
      })
        .catch((err) => {
          this.pending = false;
        })
    }
  }
}
</script>

<style lang="scss">
.base-window-content,
.task-feedback-dialog {
  height: 100%;
  .form-view-row {
    padding: 6px 0px;

    .degree-item,
    .tag-item {
      width: auto !important;
      margin-right: 16px;
      cursor: pointer;
    }

    .tag-item {
      margin-right: 0px;
    }
  }

  .close-task-btn {
    max-width: 120px !important;
  }
}

.evaluate-degree-img {
  width: 24px;
  height: 24px;
  margin-right: 2px;
  display: inline-block;
  vertical-align: middle;

  background: url(../../../../../assets/img/task/review-degree.png) no-repeat;
  background-size: 24px 144px;

  &.review-degree-satisfy {
    background-position: 0 0;
  }

  &.review-degree-commonly {
    background-position: 0 -24px;
  }

  &.review-degree-unsatisfy {
    background-position: 0 -48px;
  }

  &.review-degree-satisfy-active {
    background-position: 0 -72px;
  }

  &.review-degree-commonly-active {
    background-position: 0 -96px;
  }

  &.review-degree-unsatisfy-active {
    background-position: 0 -120px;
  }
}

.star-evaluate-row-content {
  flex: 1;

  .star-evaluate-row {
    display: flex;
    margin-bottom: 10px;

    .star-title {
      width: 86px;
      margin-right: 6px;
    }
  }
}

.evaluate-tag {
  .evaliate-tag-item {
    display: inline-block;
    padding: 2px 8px;
    margin: 0 10px 10px 0;
    font-size: 12px;
    border: 1px solid #e5e5e5;
    background-color: #f8f7f6;
    border-radius: 2px;
    color: #757575;
  }

  .evaliate-tag-active,
  input[type="checkbox"]:checked ~ span {
    color: #00d1d3;
    background-color: #f5fffd;
    border-color: #00d1d3;
  }
}
</style>
